package cn.pconline.autoclub.web.wap;

import cn.pconline.autoclub.config.SystemConfig;
import cn.pconline.autoclub.entity.Gift;
import cn.pconline.autoclub.entity.GiftConversion;
import cn.pconline.autoclub.entity.User;
import cn.pconline.autoclub.service.GiftService;
import cn.pconline.autoclub.service.MemberService;
import cn.pconline.autoclub.util.AppUtils;
import cn.pconline.autoclub.util.DateUtils;
import cn.pconline.autoclub.util.Pager;
import cn.pconline.autoclub.util.Regex;
import cn.pconline.autoclub.util.WebUtils;
import cn.pconline.autoclub.web.UserAuth;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.gelivable.webmvc.JSONBuilder;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/wap/gift")
public class GiftAction {

    @Autowired
    private GiftService giftService;
    @Autowired
    private UserAuth userAuth;
    @Autowired
    private MemberService memberService;
    @Autowired
    private SystemConfig systemConfig;
    private static final String ERROR_PAGE_REDIRECT_URL = "redirect:http://m.pcauto.com.cn/x/404/";
    private static final int STATUS_FORM_ERROR = -3; //表单验证错误
    private static final int STATUS_TEXT_ERROR = -4;//纯文本提示错误码
    private static final int STATUS_NOCOMMODITY = -1;//没货
    private static final int STATUS_NOGOLD = -2;//金币不足
    private static final org.slf4j.Logger log = LoggerFactory.getLogger(GiftAction.class);

    private String getLoginUrl(String returnUri) {
        return systemConfig.getUcWapRoot() + "/passport/login.jsp?return=" + systemConfig.getWapRoot() + returnUri;
    }

    /**
     * 返回礼品列表方法
     *
     * @param:
     * @param req
     * @param:
     * @param resp
     * @return: String
     */
    @RequestMapping(value = "/listGift")
    public String listGift(HttpServletRequest req, HttpServletResponse resp) {
        int pageNo = WebUtils.paramInt(req, "pageNo", 1);
        int pageSize = WebUtils.paramInt(req, "pageSize", 4);
        Pager<Gift> pager = giftService.listGift(Gift.STATUS_UP, pageNo, pageSize);
        User user = userAuth.getUser(req, resp);
        String commonSessionId = cn.pconline.passport2.util.WebUtils.getCookie(req, systemConfig.getUserSessionName());
        long gold = 0;
        if (user != null && user.getUid() > 0) {
            gold = giftService.getCoinsByUserId(commonSessionId, user.getUid());
        }
        int countConversion = giftService.countConversion(user.getUid());
        req.setAttribute("countConversion", countConversion);
        req.setAttribute("gold", gold);
        req.setAttribute("user", user);
        req.setAttribute("pager", pager);
        req.setAttribute("total", pager.getTotal());
        return "template/wap/gift/gift_list";
    }

    /**
     * 返回兑换记录列表方法
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/listRecord", method = RequestMethod.GET)
    public String listRecord(HttpServletRequest request, HttpServletResponse response) {
        int pageSize = WebUtils.paramInt(request, "pageSize", 10,1,100);
        int pageNo = WebUtils.paramInt(request, "pageNo", 1);
        // 判断用户是否登录
        User userLogin = userAuth.getUser(request, response);
        if (userLogin == null || userLogin.getUid() == 0L) {
            return "redirect:" + getLoginUrl("/duihuan/record/");
        }
        Pager<GiftConversion> pager = giftService.pagerLoadConversionByUserId(userLogin.getUid(), pageNo, pageSize);
        if (pager != null) {
            for (GiftConversion giftConversion : pager.getResultList()) {
                Gift gift = giftService.find(giftConversion.getGiftId());
                gift.setGiftUrl(gift.getGiftUrl60x60());//用60*60显示
                if (gift != null) {
                    giftConversion.setGift(gift);
                }
            }
        }
        request.setAttribute("isMore", pager.getPageNo() < pager.getPageCount());
        request.setAttribute("pager", pager);
        return "template/wap/gift/recordList";
    }

    /**
     * 根据用户ID获取用户兑换礼品详细记录
     *
     * @param request
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/listConversionHistoryByUserId", method = RequestMethod.GET)
    public void listConversionHistoryByUserId(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);
        //获取相关参数
        String callback = WebUtils.param(request, "callback", "");
        int pageSize = WebUtils.paramInt(request, "pageSize", 6);
        int pageNo = WebUtils.paramInt(request, "pageNo", 1);
        JSONArray jsonArray = new JSONArray();
        JSONObject json = new JSONObject();
        // 判断用户是否登录
        User userLogin = userAuth.getUser(request, response);
        if (userLogin == null || userLogin.getUid() == 0L) {
            json.put("code", AppUtils.STATUS_FAIL);
            json.put("message", "用户ID不能为空");
            return;
        }
        Pager<GiftConversion> pager = giftService.pagerLoadConversionByUserId(userLogin.getUid(), pageNo, pageSize);
        if (pager != null) {
            for (GiftConversion giftConversion : pager.getResultList()) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("id", giftConversion.getConversionId());//兑换礼品记录ID
                Gift gift = giftService.find(giftConversion.getGiftId());
                if (gift != null) {
                    jsonObject.put("img", gift.getGiftUrl60x60());//礼品URL
                    jsonObject.put("name", gift.getName());//礼品名称
                }
                jsonObject.put("cost", giftConversion.getGold());//礼品兑换金币
                jsonObject.put("time", DateUtils.formatYYMMDDHM(giftConversion.getCreateAt()));//礼品兑换时间
                jsonObject.put("status", giftConversion.getStatus());//礼品状态

                jsonArray.add(jsonObject);
            }
        }
        json.put("data", jsonArray);
        json.put("total", pager.getTotal());
        json.put("pageNo", pager.getPageNo());
        json.put("pageSize", pager.getPageSize());
        json.put("code", AppUtils.STATUS_OK);
        json.put("message", "成功获取用户礼品兑换历史列表！");
        printMsg(response, json.toString(), callback);
    }

    /**
     * wap分页获取兑换礼品
     *
     * @param:
     * @param req
     * @param:
     * @param resp
     * @return: String
     */
    @ResponseBody
    @RequestMapping(value = "/pageGift", method = RequestMethod.GET)
    public void pageGift(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);
        String callback = WebUtils.param(request, "callback", "");
        int pageSize = WebUtils.paramInt(request, "pageSize", 4);
        int pageNo = WebUtils.paramInt(request, "pageNo", 1);
        JSONArray jsonArray = new JSONArray();
        JSONObject json = new JSONObject();
        try {
            Pager<Gift> pager = giftService.listGift(Gift.STATUS_UP, pageNo, pageSize);
            if (pager != null) {
                List<Gift> list = pager.getResultList();
                if (list != null && list.size() > 0) {
                    for (Gift gift : list) {
                        if (gift != null && gift.getGiftId() > 0) {
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("giftId", gift.getGiftId());
                            jsonObject.put("name", gift.getName());
                            jsonObject.put("giftUrl", gift.getGiftUrl());
                            jsonObject.put("total", gift.getTotal());
                            jsonObject.put("gold", gift.getGold());
                            jsonObject.put("curNum", gift.getCurNum());
                            jsonArray.add(jsonObject);
                        }
                    }
                }
            }
            json.put("data", jsonArray);
            json.put("code", AppUtils.STATUS_OK);
            json.put("total", pager.getTotal());
            json.put("pageCount", pager.getPageCount());
            printMsg(response, json.toString(), callback);
        } catch (Exception e) {
            json.put("data", jsonArray);
            json.put("total", 0);
            json.put("pageCount", 0);
            printMsg(response, json.toString(), callback);
        }
    }

    /**
     * 返回相关Json信息
     *
     * @param resp
     * @param str
     * @param callback
     */
    private void printMsg(HttpServletResponse resp, String str, String callback) {
        try {
            java.io.PrintWriter w = resp.getWriter();
            if (StringUtils.isNotBlank(callback)) {
                w.print(callback + "(" + str + ")");
            } else {
                w.print(str);
            }
            w.flush();
            w.close();
        } catch (IOException ex) {
            log.error("throw exception where set response message!", ex);
        }
    }

    /**
     * 跳转到申请页面
     *
     * @param:
     * @param req
     * @param:
     * @param resp
     * @return: String
     */
    @RequestMapping(value = "/applyGift")
    public String applyGift(HttpServletRequest req, HttpServletResponse resp) {
        long giftId = WebUtils.paramLong(req, "giftId", 0);
        Gift gift = giftService.find(giftId);
        User user = userAuth.getUser(req, resp);
        if (gift == null) {
            return ERROR_PAGE_REDIRECT_URL;
        }
        req.setAttribute("user", user);
        req.setAttribute("gift", gift);

        return "template/wap/gift/applyGift";
    }

    /**
     * 提交兑换申请
     *
     * @param:
     * @param req
     * @param:
     * @param resp
     * @return: String
     */
    @RequestMapping(value = "/createConversion", method = RequestMethod.POST)
    public void createConversion(HttpServletRequest req, HttpServletResponse resp) {
        long giftId = WebUtils.paramLong(req, "giftId", 0);
        String trueName = WebUtils.param(req, "trueName", "");
        String province = WebUtils.param(req, "province", "");
        String city = WebUtils.getAreaPlaceByReq(req, "city", "");
        String address = WebUtils.param(req, "address", "");
        String postcode = WebUtils.param(req, "postcode", "");
        String phone = WebUtils.param(req, "phone", "");
        int num = WebUtils.paramInt(req, "num", 0);
        String callback = WebUtils.param(req, "callback", "");
        int ADDRESS_LENGTH = 100, INPUT_MAX_LENGTH = 30;
        if(num == 0){
        	  printMsg(resp, "num", STATUS_FORM_ERROR, "请填写正确的兑换数", callback);
        	  return;
        }
        if (StringUtils.isBlank(trueName)) {
            printMsg(resp, "trueName", STATUS_FORM_ERROR, "请填写真实姓名", callback);
            return;
        } else if (trueName.length() > INPUT_MAX_LENGTH) {
            printMsg(resp, "trueName", STATUS_FORM_ERROR, "姓名太长啦", callback);
            return;
        }
        if (StringUtils.isBlank(province)) {
            printMsg(resp, "province", STATUS_FORM_ERROR, "请填写省份", callback);
            return;
        } else if (province.length() > INPUT_MAX_LENGTH) {
            printMsg(resp, "province", STATUS_FORM_ERROR, "非法省份名称", callback);
            return;
        }
        if (StringUtils.isBlank(city)) {
            printMsg(resp, "city", STATUS_FORM_ERROR, "请填写城市", callback);
            return;
        } else if (province.length() > INPUT_MAX_LENGTH) {
            printMsg(resp, "city", STATUS_FORM_ERROR, "非法城市名称", callback);
            return;
        }
        if (StringUtils.isBlank(address)) {
            printMsg(resp, "address", STATUS_FORM_ERROR, "请填写地址", callback);
            return;
        } else if (address.length() > ADDRESS_LENGTH) {
            printMsg(resp, "address", STATUS_FORM_ERROR, "详细地址不能超过" + ADDRESS_LENGTH + "字符", callback);
            return;
        }
        if (StringUtils.isBlank(postcode) || !postcode.matches(Regex.postcode.value)) {
            printMsg(resp, "postcode", STATUS_FORM_ERROR, "请填写正确的邮政编码", callback);
            return;
        }
        if (StringUtils.isBlank(phone) || !phone.matches(Regex.cellphone.value)) {
            printMsg(resp, "phone", STATUS_FORM_ERROR, "请填写正确的手机号码", callback);
            return;
        }
        User user = userAuth.getUser(req, resp);
        if (user == null || user.getUid() == 0) {
            printMsg(resp, "", AppUtils.STATUS_NOLOGIN_ERROR, "请先登录", callback);
            return;
        }
        Gift gift = giftService.find(giftId);
        if (gift == null) {
            printMsg(resp, "", STATUS_TEXT_ERROR, "找不到该礼品", callback);
            return;
        }
        String trueAddress = province + city + address;
        int curNum = gift.getCurNum();
        if (curNum < 1) {
            printMsg(resp, "", STATUS_NOCOMMODITY, "很抱歉，礼品已经被兑换完毕了", callback);
            return;
        }
        if (curNum < num) {
            printMsg(resp, "", STATUS_NOCOMMODITY, "很抱歉，只剩"+ curNum +"个礼品可以兑换了", callback);
            return;
        }
        // 判断金币是否足够
        String commonSessionId = cn.pconline.passport2.util.WebUtils.getCookie(req, systemConfig.getUserSessionName());
        long gold = giftService.getCoinsByUserId(commonSessionId, user.getUid());
        if (gold < gift.getGold()*num) {
            printMsg(resp, "", STATUS_NOGOLD, "抱歉，您还差<em>" + (gift.getGold()*num - gold) + "</em>金币", callback);
            return;
        }
        GiftConversion conversion = giftService.createConversion(user.getUid(), gift, trueName, trueAddress, postcode, phone,num);
        if (conversion != null) {
            // 与任务接口做扣金币操作,根据结果决定是否修改订单状态
            long isSuccess = 0;
            boolean isFree = false;//是否为免费礼品
            if (gift.getGold() == 0) {//如果是免费礼品，不需要调用任务系统接口扣金币
                isFree = true;
            } else {//扣金币操作
                isSuccess = giftService.updateUserGold(commonSessionId, user.getUid(), gift.getGold()*num, num, gift.getName()); //扣金币结果
            }
            if (isSuccess > Gift.STATUS_GOLD_OK || isFree) {
                int count = giftService.updateConversionToNormal(conversion, isSuccess, num);
                if (count > 0) {
                    printMsg(resp, "", AppUtils.STATUS_OK, "兑换成功", callback);
                } else {
                    printMsg(resp, "", STATUS_TEXT_ERROR, "兑换失败", callback);
                }
            } else if (isSuccess == Gift.STATUS_GOLD_ERROR) {
                printMsg(resp, "", STATUS_TEXT_ERROR, "兑换失败", callback);
            } else if (isSuccess == Gift.STATUS_GOLD_FAIL) {
                printMsg(resp, "", STATUS_TEXT_ERROR, "兑换失败,金币不足", callback);
            } else {
                printMsg(resp, "", STATUS_NOGOLD, "兑换失败", callback);
            }
        } else {
            printMsg(resp, "", STATUS_TEXT_ERROR, "兑换失败", callback);
        }

    }

    /**
     * ajax 统一返回方法
     *
     * @param:
     * @param req
     * @param:
     * @param resp
     * @return: String
     */
    private void printMsg(HttpServletResponse resp, String field, int statusCode, String msg, String callback) {
        resp.setCharacterEncoding("UTF-8");
        try {
            PrintWriter out = resp.getWriter();
            String json = new JSONBuilder()
                    .put("statusCode", statusCode)
                    .put("message", msg)
                    .put("field", field)
                    .toString();
            if (StringUtils.isBlank(callback)) {
                out.println(json);
            } else {
                out.println(callback + "(" + json + ")");
            }
        } catch (IOException ex) {
            log.error("set printMsg fail!", ex);
        }
    }
}
